var app = getApp();
var util = require('../../utils/util.js');
var chooseFlag = true;

Page({
    data: {
        id:'',
        catesArr:[],
        catesArrShow: [],
        labelnameArr:[],
        labelnameShow:'',
        showOtherTime:false,
        showImgToolbar:true,
        showImgResize:true,
        showImgSize:true,
        bigImg:[],
        thumbs:[],
        form:{
            token: '',//token
            goodsname: '',//商品名称
            cate_mult: [],//商品分类
            subtitle: '',//商品简介
            brandintro: '',//商品品牌
            sizeintro: '',//商品规格
            placeintro: '',//商品产地
            shopnumber: '',//商品编号
            print_sub_title: '',//商品短标题
            big_img:'',//商品大图
            thumbs:[],//商品主图
            grounding: '',//商品状态
            is_index_show: '',//首页推荐
            is_shop_show:'',//店铺推荐
            is_take_vipcard: '',//付费
            price:'',//商品价格
            card_price: '',//付费会员价
            productprice: '',//原价
            costprice: '',// 成本价
            sales: '',//已售
            pick_up_type:'',//提货时间
            pick_up_modify:'',//自定义提货时间
            labelname:'',//自定义标签
            dispatchtype:1,//自定义邮费
            dispatchprice:'',//自定义邮费
            one_limit_count: '',//单次限购
            total_limit_count: '',//历史限购
            is_only_express:'',//仅快递
            community_head_commission:'',//团长独立提成
            is_all_sale:'',//所有团长可售
            codes:'',//商品编码
            weight:'',//商品重量
            total:'',//库存
            begin_time: "",//开始时间
            end_time: "",//结束事件
            changeTextDetail:'',//文字介绍
            changeImgDetail:[],//图片介绍
            content:''//详情介绍
        }
    },
    onLoad: function (options) {
        console.log(options);
        if(options.id){
            this.setData({
                id: options.id
            })
        }
        this.getData();
    },
    onEditorReady() {
        const that = this
        wx.createSelectorQuery().select('#editor').context(function (res) {
            console.log(res);
            that.editorCtx = res.context
        }).exec()
    },
    getData: function () {
        let that = this;
        let token = wx.getStorageSync('token');
        var up = "form.token";
        that.setData({
            [up]: token
        })

        wx.showLoading();
        app.util.request({
            url: 'entry/wxapp/index',
            data: {
                controller: 'supplymobile.supply_add_getinfo',
                token
            },
            dataType: 'json',
            success: function (res) {
                that.setData({
                    catesArr: res.data.category,
                    labelnameArr: res.data.labels
                })
                console.log(that.data.catesArr);
                wx.hideLoading();


                if (that.data.id) {
                    let id = that.data.id;
                    app.util.request({
                        url: 'entry/wxapp/index',
                        data: {
                            controller: 'supplymobile.supply_add_getgoods',
                            token,
                            id
                        },
                        dataType: 'json',
                        success: function (res) {
                            if (res.data.code == 0) {
                                delete res.data.data.content; 
                                var formData = res.data.data;
                                formData.token = token;
                                that.setData({
                                    form: formData
                                })
                                var token = "form.token";
                                that.setData({
                                    [token]: token
                                })
                                // console.log(that.data.form);

                                var catesArr = that.data.catesArr;
                                var arr = [], id = [];
                                var up = "form.cate_mult";
                                // console.log(formData.cate_mult);
                                for (var i in formData.cate_mult) {
                                    for (var ix in catesArr) {
                                        // console.log(formData.cate_mult[i]);
                                        if (formData.cate_mult[i] == catesArr[ix].id) {
                                            arr.push({ id: catesArr[ix].id, name: catesArr[ix].name, idx: ix });
                                            id.push(catesArr[ix].id);
                                            catesArr.splice(ix, 1);
                                            // console.log(arr);
                                            break;
                                        }
                                    }
                                }

                                var labelnameArr = that.data.labelnameArr;
                                var up = "form.labelname";
                                for (var i in labelnameArr){
                                    if (formData.labelname.id == labelnameArr[i].id){
                                        that.setData({
                                            [up]: labelnameArr[i].id,
                                            labelnameShow: labelnameArr[i].tagname
                                        });
                                        break;
                                    }
                                }

                                that.setData({
                                    catesArrShow: that.data.catesArrShow.concat(arr),
                                    [up]: that.data.form.cate_mult.concat(id)
                                });

                                that.setData({
                                    catesArr: catesArr
                                })

                                if (formData.begin_time != ''){
                                    var up = "form.begin_time";
                                    console.log();
                                    that.setData({
                                        [up]: util.formatTimeWx(formData.begin_time * 1000, 'Y-M-D h:m:s')
                                    })
                                }

                                if (formData.end_time != '') {
                                    var up = "form.end_time";
                                    console.log();
                                    that.setData({
                                        [up]: util.formatTimeWx(formData.end_time * 1000, 'Y-M-D h:m:s')
                                    })
                                }

                                if(formData.big_img != ''){
                                    var bigImg = [];
                                    bigImg.push(formData.big_img);
                                    that.setData({
                                        bigImg: bigImg
                                    })
                                }
                                
                                if (formData.thumbs && formData.thumbs.length>0){
                                    var thumbs = [];
                                    var up = "form.thumbs";
                                    for(var i in formData.thumbs){
                                        thumbs.push(formData.thumbs[i].image);
                                    }
                                    that.setData({
                                        thumbs: thumbs,
                                        [up]: thumbs
                                    })
                                    console.log(that.data.thumbs);
                                }
                            }
                        }
                    })
                }else{
                    var groundingnum = "form.grounding",
                        is_index_shownum = "form.is_index_show",
                        pick_up_typenum = "form.pick_up_type";
                    that.setData({
                        [groundingnum]: 1,
                        [is_index_shownum]:1,
                        [pick_up_typenum]:0
                    })
                }
            }
        })
    },
    bindtagChange:function(e){
        var index = e.detail.value, labelnameArr = this.data.labelnameArr;
        var up = "form.labelname";
        this.setData({
            [up]: labelnameArr[index].id,
            labelnameShow: labelnameArr[index].tagname
        });
    },
    removeBigimg:function(e){
        var up = "form.big_img";
        this.setData({
            [up]: '',
            bigImg: false
        });
    },
    bindtypeChange:function(e){
        var index = e.detail.value,catesArr = this.data.catesArr;
        var arr = [],id = [];
        arr.push({ id: catesArr[index].id, name: catesArr[index].name, idx: index });
        id.push(catesArr[index].id);
        var up = "form.cate_mult";
        this.setData({
            catesArrShow: this.data.catesArrShow.concat(arr),
            [up]: this.data.form.cate_mult.concat(id)
        });
        catesArr.splice(index, 1);
        this.setData({
            catesArr: catesArr
        })
    },
    addCatesArr:function(e){
        var item = e.currentTarget.dataset.item, 
            idx = e.currentTarget.dataset.idx,
            index = e.currentTarget.dataset.index,
            catesArr = this.data.catesArr,
            cates = this.data.form.cate_mult,
            catesArrShow = this.data.catesArrShow;
            catesArrShow.splice(index, 1);
            
            cates.splice(index, 1);
            catesArr.splice(idx, 0, item);
            var up = "form.cate_mult";
            this.setData({
                catesArrShow: catesArrShow,
                catesArr: catesArr,
                [up]: cates
            })
    },
    shopStatus:function(e){
        var index = e.detail.value;
        var up = "form.grounding";
        this.setData({
            [up]: index
        });
    },
    indexShow:function(e){
        var index = e.detail.value;
        var up = "form.is_index_show";
        this.setData({
            [up]: index
        });
    },
    shopShow: function (e) {
        var index = e.detail.value;
        var up = "form.is_shop_show";
        this.setData({
            [up]: index
        });
    },
    changePay:function(e){
        console.log(e);
        var index = e.detail.value;
        var up = "form.is_take_vipcard";
        if (index == ''){
            this.setData({
                [up]: 0
            });
        }else{
            this.setData({
                [up]: 1
            });
        }
    },
    onExpress: function (e) {
        var index = e.detail.value;
        var up = "form.is_only_express";
        if (index == '') {
            this.setData({
                [up]: 0
            });
        } else {
            this.setData({
                [up]: 1
            });
        }
    },
    allSale: function (e) {
        console.log(e);
        var index = e.detail.value;
        var up = "form.is_all_sale";
        if (!index) {
            this.setData({
                [up]: 0
            });
        } else {
            this.setData({
                [up]: 1
            });
        }
    },
    getShopTime:function(e){
        console.log(e);
        var index = e.detail.value, that = this, up = "form.pick_up_type";
        this.setData({
            [up]:index
        });
    },
    chooseImage: function () {
        chooseFlag = false;
    },
    changeImg: function (e) {
        console.log(e);
        var up = "form.thumbs";
        this.setData({
            [up]: e.detail.value
        });
    },
    changeImgMain:function(e){
        var up = "form.big_img";
        this.setData({
            [up]: e.detail.value
        });
    },
    changeImgDetail:function(e){
        var up = "form.changeImgDetail";
        this.setData({
            [up]: e.detail.value
        });
    },
    goodsInput:function(e){
        console.log(e);
        var name = e.currentTarget.dataset.name;
        var up = "form."+name;
        this.setData({
            [up]: e.detail.value
        });
    },
    /**
   * 提交
   */
    subForm: function () {
        
        let { goodsname, cate_mult, subtitle, brandintro, sizeintro, placeintro, shopnumber, print_sub_title, big_img, thumbs, grounding, is_index_show, is_shop_show, is_take_vipcard, price, card_price, productprice, costprice, sales, pick_up_type, pick_up_modify, labelname, dispatchtype, dispatchprice, one_limit_count, total_limit_count, community_head_commission, is_all_sale,is_only_express,codes,weight,total,content,begin_time,end_time } = this.data.form;
        let that = this;
        if (goodsname == '') {
            wx.showToast({
                title: '请输入商品名称',
                icon: 'none'
            })
            return;
        }

        if (big_img.length <= 0) {
            wx.showToast({
                title: '请上传商品大图',
                icon: 'none'
            })
            return;
        }
        if (thumbs.length <= 0) {
            wx.showToast({
                title: '请选上传商品主图',
                icon: 'none'
            })
            return;
        }

        if (price == '') {
            wx.showToast({
                title: '请输入商品价格',
                icon: 'none'
            })
            return;
        }

        if (begin_time > end_time){
            wx.showToast({
                title: '团购开始时间不可大于结束时间',
                icon: 'none'
            })
            return;
        }
        const token = wx.getStorageSync('token');
        console.log(token);
        console.log(that.data.token);
        
        console.log(that.data.form.thumbs);
        console.log(that.data.id);
        if(that.data.id>0){
            let id = that.data.id,ok=1;
            let data = { id, ok, goodsname, cate_mult, subtitle, brandintro, sizeintro, placeintro, shopnumber, print_sub_title, big_img, thumbs, grounding, is_index_show, is_shop_show, is_take_vipcard, price, card_price, productprice, costprice, sales, pick_up_type, pick_up_modify, labelname, dispatchtype, dispatchprice, one_limit_count, is_only_express, total_limit_count, community_head_commission, is_all_sale, codes, weight, total, token, begin_time, end_time };
            app.util.request({
                url: 'entry/wxapp/index',
                method: 'post',
                data: {
                    controller: 'supplymobile.supply_edit_goods',
                    ...data
                },
                dataType: 'json',
                success: function (res) {
                    console.log(res);
                    if (res.data.code == 0) {
                        app.util.message('提交成功', 'redirect:/lionfish_comshop/moduleB/supply/goodsManage', 'success');
                    } else {
                        app.util.message(res.data.msg || '提交失败', '', 'error');
                        return;
                    }
                }
            })
        }else{
            var html = that.data.form.changeTextDetail;
            for (var i in that.data.form.changeImgDetail){
                html += '<img src="' + that.data.form.changeImgDetail[i]+'" />';
            }
            let data = { goodsname, cate_mult, subtitle, brandintro, sizeintro, placeintro, shopnumber, print_sub_title, big_img, thumbs, grounding, is_index_show, is_shop_show, is_take_vipcard, price, card_price, productprice, costprice, sales, pick_up_type, pick_up_modify, labelname, dispatchtype, dispatchprice, one_limit_count, total_limit_count, is_only_express, community_head_commission, is_all_sale, codes, weight, total, content: html, token, begin_time, end_time };
            app.util.request({
                url: 'entry/wxapp/index',
                method: 'post',
                data: {
                    controller: 'supplymobile.addGoods',
                    ...data
                },
                dataType: 'json',
                success: function (res) {
                    console.log(res);
                    if (res.data.code == 0) {
                        app.util.message('提交成功', 'redirect:/lionfish_comshop/moduleB/supply/goodsManage', 'success');
                    } else {
                        app.util.message(res.data.msg || '提交失败', '', 'error');
                        return;
                    }
                }
            })
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        
    },
    /**
   * 开始时间
   */
    beginTimePicker: function (e) {
        var up = "form.begin_time";
        console.log();
        this.setData({
            [up]: e.detail
        })
    },

    /**
     * 开始时间
     */
    endTimePicker: function (e) {
        var up = "form.end_time";
        console.log();
        this.setData({
            [up]: e.detail
        })
    },
})